package io.renren.softpark.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunlong.common.utils.PageUtils;
import com.yunlong.common.utils.Query;
import io.renren.softpark.dao.*;
import io.renren.softpark.dto.*;
import io.renren.softpark.entity.*;
import io.renren.softpark.form.AddColumnForm;
import io.renren.softpark.service.ColumnService;
import io.renren.softpark.util.MenuUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Service("columnService")
public class ColumnServiceImpl extends ServiceImpl<ColumnDao, ColumnEntity> implements ColumnService {

    @Autowired
    SortDao sortDao;

    @Autowired
    ColumnDao columnDao;

    @Autowired
    PlatesDao platesDao;

    @Autowired
    IntroduceDao introduceDao;

    @Autowired
    CommentDao commentDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ColumnEntity> page = this.page(
                new Query<ColumnEntity>().getPage(params),
                new QueryWrapper<ColumnEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public List<VerifyColumnDto> verifyColumn(Map<String, Object> params) {
        IPage<ColumnEntity> columnPage = this.page(
                new Query<ColumnEntity>().getPage(params),
                new QueryWrapper<ColumnEntity>()
        );
        List<ColumnEntity> records = columnPage.getRecords();
        List<SortEntity> sortPage = sortDao.selectList(new QueryWrapper<>());
        List<AddColumnDto> columnDtos = listTree();
        List<VerifyColumnDto> verify = records.stream().map((r) -> {
            int[] parentIds = new int[2];
            VerifyColumnDto verifyColumn = new VerifyColumnDto();
            BeanUtils.copyProperties(r, verifyColumn);
            List<String> collect = sortPage.stream().filter((s) ->
                    s.getSortId() == r.getParentId()
            ).map((s) -> {
                parentIds[0] = s.getSortId();
                verifyColumn.setParentId(parentIds);
                return s.getSortName();
            }).collect(Collectors.toList());
            for (int i = 0; i < columnDtos.size(); i++) {
                for (int j = 0; j < columnDtos.get(i).getChilds().size(); j++) {
                    if (verifyColumn.getParentId()[0] == columnDtos.get(i).getChilds().get(j).getMenuId()) {
                        parentIds[0] = i;
                        parentIds[1] = j;
                        verifyColumn.setParentId(parentIds);
                    }
                }
            }
            verifyColumn.setSortName(collect.get(0));
            return verifyColumn;
        }).collect(Collectors.toList());
        return verify;
    }

    /**
     * 二级菜单
     *
     * @return
     */
    @Override
    public List<AddColumnDto> listTree() {
        //查询所有审核通过的column
//        List<ColumnEntity> columnEntities = columnDao.selectList(
//                new QueryWrapper<ColumnEntity>().eq("verify",1));
        List<PlatesEntity> platesEntities = platesDao.selectList(new QueryWrapper<>());
        List<SortEntity> sortEntities = sortDao.selectList(new QueryWrapper<>());
        List<AddColumnDto> collect = platesEntities.stream().map((p) -> {
            List<AddColumnDto> collectSort = sortEntities.stream().filter((s) ->
                    p.getPlateId() == s.getParentId()
            ).map((s) -> {
                AddColumnDto addColumnDto = new AddColumnDto();
                addColumnDto.setMenuName(s.getSortName());
                addColumnDto.setMenuId(s.getSortId());
                return addColumnDto;
            }).collect(Collectors.toList());
            AddColumnDto addColumnDto = new AddColumnDto();
            addColumnDto.setMenuName(p.getPlateName());
            addColumnDto.setChilds(collectSort);
            addColumnDto.setMenuId(p.getPlateId());
            return addColumnDto;
        }).collect(Collectors.toList());
        return collect;

    }

    @Override
    public ColumnInfoDto getEditColumn(String columnId) {
        ColumnEntity columnEntity = columnDao.selectById(columnId);
        ColumnInfoDto columnInfoDto = new ColumnInfoDto();
        BeanUtils.copyProperties(columnEntity, columnInfoDto);
        List<AddColumnDto> columnDtos = listTree();
        int[] parentId = new int[2];
        for (int i = 0; i < columnDtos.size(); i++) {
            for (int j = 0; j < columnDtos.get(i).getChilds().size(); j++) {
                if (columnEntity.getParentId() == columnDtos.get(i).getChilds().get(j).getMenuId()) {
                    parentId[0] = i + 1;
                    parentId[1] = columnDtos.get(i).getChilds().get(j).getMenuId();
                }
            }
        }
        columnInfoDto.setParentId(parentId);
        return columnInfoDto;
    }

    @Override
    public void updateColumnById(ColumnInfoDto columnInfoDto) {
        ColumnEntity columnEntity = new ColumnEntity();
        BeanUtils.copyProperties(columnInfoDto, columnEntity);
        columnEntity.setParentId(columnInfoDto.getParentId()[1]);
        columnDao.update(columnEntity, new QueryWrapper<ColumnEntity>()
                .eq("column_id", columnInfoDto.getColumnId()));
    }

    @Override
    public void saveColumn(AddColumnForm addColumnForm) {
        String columnId = UUID.randomUUID().toString().replace("-", "");
        String introduceId = UUID.randomUUID().toString().replace("-", "");
        ColumnEntity columnEntity = new ColumnEntity();
        BeanUtils.copyProperties(addColumnForm, columnEntity);
        columnEntity.setColumnId(columnId);
        columnEntity.setIntroduceId(introduceId);
        columnEntity.setRecommend(0);
        columnEntity.setVerify(1);
        columnDao.insert(columnEntity);
        IntroduceEntity introduceEntity = new IntroduceEntity();
        introduceEntity.setUpdateLog(new SimpleDateFormat("yyyy-MM-dd HH:mm")
                .format(new Date()) + ":创建了" + addColumnForm.getColumnName());
        introduceEntity.setIntroduceId(introduceId);
        introduceDao.insert(introduceEntity);
    }

    /**
     * 获取栏目的详细信息
     *
     * @param columnId
     * @return
     */
    @Override
    public ColumnDetailDto getDetailData(String columnId) {
        ColumnDetailDto columnDetailDto = new ColumnDetailDto();
        ColumnEntity columnEntity = columnDao.selectOne(new QueryWrapper<ColumnEntity>().eq("COLUMN_ID", columnId));
        List<PlatesEntity> platesEntityList = platesDao.selectList(new QueryWrapper<PlatesEntity>());
        List<String> sortList = new ArrayList<>();
        List<SortEntity> sortEntityList = sortDao.selectList(new QueryWrapper<SortEntity>());
        List<CommentEntity> commentEntityList = commentDao.selectList(new QueryWrapper<CommentEntity>().eq("COLUMN_ID", columnId));;
        sortList.add("sortName:");
        for (SortEntity sortEntity : sortEntityList) {
            String sortName = sortEntity.getSortName();
            sortList.add(sortName);
        }

        /**
         * 栏目基本信息
         */
        columnDetailDto.setColumnId(columnEntity.getColumnId());
        columnDetailDto.setColumnName(columnEntity.getColumnName());
        columnDetailDto.setColumnLogo(columnEntity.getColumnLogo());
        columnDetailDto.setShowPic(columnEntity.getShowPic());
        columnDetailDto.setDownloads(columnEntity.getDownloads());
        columnDetailDto.setRecommend(columnEntity.getRecommend());
        columnDetailDto.setVerify(columnEntity.getVerify());
        columnDetailDto.setWebIntroduce(columnEntity.getWebIntroduce());
        columnDetailDto.setColumnWeb(columnEntity.getColumnWeb());
        columnDetailDto.setUserId(columnEntity.getUserId());
        columnDetailDto.setLicense(columnEntity.getLicense());
        columnDetailDto.setColumnType(columnEntity.getColumnType());
        List<String> parentIdList = new ArrayList<>();
        parentIdList.add(sortList.get(columnEntity.getParentId()));
        parentIdList.add(columnEntity.getParentId().toString());
        //设置板块-分类ID
        columnDetailDto.setParentId(parentIdList);
        //设置分类名
        columnDetailDto.setParentName(sortList.get(columnEntity.getParentId()));
        //设置分类菜单
        columnDetailDto.setPlatesList(MenuUtil.getTwoLevelMenu(sortEntityList, platesEntityList));

        /**
         * 回显栏目
         */

        /**
         * 获取对应的Introduce
         */
        String introduceId = columnEntity.getIntroduceId();
        IntroduceEntity introduceEntity = introduceDao.selectDataForDetailColumn(introduceId);
        columnDetailDto.setBriefIntro(introduceEntity.getBriefIntro());
        columnDetailDto.setCharacter(introduceEntity.getCharacter());
        columnDetailDto.setFunction(introduceEntity.getFunction());
        columnDetailDto.setUpdateLog(introduceEntity.getUpdateLog());
        /**
         * 设置对应的评论信息
         */
        List<CommentDto> commentDtoList = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for (CommentEntity commentEntity : commentEntityList) {
            CommentDto commentDto = new CommentDto();
            commentDto.setContent(commentEntity.getContent());
            commentDto.setTime(simpleDateFormat.format(commentEntity.getTime()).toString());
            commentDto.setUserId(commentEntity.getUserId());
            commentDto.setVerify(commentEntity.getVerify());
            commentDtoList.add(commentDto);
        }
        columnDetailDto.setCommentDtoList(commentDtoList);
        return columnDetailDto;

    }

}